package com.c201801020208.ybl.Login.Activity;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.c201801020208.ybl.R;
import com.c201801020208.ybl.Tool.GenerateTestUserSig;
import com.c201801020208.ybl.Tool.MD5Util;
import com.c201801020208.ybl.User.Activity.MainActivity;
import com.c201801020208.ybl.Tables.PUser;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import org.xutils.BuildConfig;
import org.xutils.x;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    EditText editText;
    EditText editText2;
    Button button;
    Button button2;
    ImageView imageView;
    ImageView imageView2;
    ImageView imageView3;
    private boolean isHideFirst = true;// 输入框密码是否是隐藏的，默认为true
    public static String image;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        x.Ext.init(getApplication());
        x.Ext.setDebug(BuildConfig.DEBUG);// 是否输出debug日志, 开启debug会影响性能.
        x.view().inject(this);//没有用到view注解可以先不用

        image = getIntent().getStringExtra("image");

        button = findViewById(R.id.button);
        button2 = findViewById(R.id.button2);
        editText = findViewById(R.id.editText2);
        editText2 = findViewById(R.id.editText);
        imageView = findViewById(R.id.imageView);
        imageView2 = findViewById(R.id.delete);
        imageView3 = findViewById(R.id.see);
        initListener();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (editText2.getText().toString().equals("") || editText.getText().toString().equals("")) {
                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
                } else {
                    //从云数据库匹配账号密码是否正确
                    BmobQuery<PUser> categoryBmobQuery = new BmobQuery<>();
                    categoryBmobQuery.addWhereEqualTo("username", editText.getText().toString());
                    categoryBmobQuery.findObjects(new FindListener<PUser>() {
                        @Override
                        public void done(List<PUser> object, BmobException e) {
                            if (e == null) {
                                if (object.get(0).getPassword().equals(MD5Util.getMD5Str(editText2.getText().toString().trim()))) {
                                    if (object.get(0).getId() == 0) {
                                        V2TIMManager.getInstance().login(editText.getText().toString(), GenerateTestUserSig.genTestUserSig(editText.getText().toString()), new V2TIMCallback() {
                                            @Override
                                            public void onError(int code, String desc) {
                                                Toast.makeText(LoginActivity.this, "登录失败, errCode = " + code + ", errInfo = " + desc, Toast.LENGTH_LONG).show();
                                            }

                                            @Override
                                            public void onSuccess() {
                                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                                intent.putExtra("username", editText.getText().toString());
                                                startActivity(intent);
                                                finish();
                                            }
                                        });
                                    } else {
                                        Toast.makeText(LoginActivity.this, "您不是个人用户哦！请在企业用户登录页面进行登录", Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    Toast.makeText(LoginActivity.this, "密码错误！：", Toast.LENGTH_LONG).show();
                                }
//                                Toast.makeText(LoginActivity.this, "查询成功：" + object.get(0).getPassword(), Toast.LENGTH_LONG).show();
                            } else {
                                Log.e("BMOB", e.toString());
//                                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            }
        });


        //注册界面
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //返回选择页面
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, SelectActivity.class);
                startActivity(intent);
                finish();

            }
        });

    }

    //设置监听器
    private void initListener() {
        editText.addTextChangedListener(textWatcher);
        editText2.addTextChangedListener(textWatcher);
        imageView2.setOnClickListener(this);
        imageView3.setOnClickListener(this);
        imageView3.setImageResource(R.drawable.d);
        imageView3.setVisibility(View.GONE);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editText.getEditableText().length() >= 1) {
                imageView2.setVisibility(View.VISIBLE);
            } else {
                imageView2.setVisibility(View.GONE);
            }
            if (editText2.getEditableText().length() >= 1) {
                imageView3.setVisibility(View.VISIBLE);
            } else {
                imageView3.setVisibility(View.GONE);
            }
        }
    };

    //点击事件（清空）
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete:
                editText.setText("");
                break;
            case R.id.see:
                if (isHideFirst == true) {
                    imageView3.setImageResource(R.drawable.c);
                    //密文
                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    editText2.setTransformationMethod(method1);
                    isHideFirst = false;
                } else {
                    imageView3.setImageResource(R.drawable.d);
                    //密文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    editText2.setTransformationMethod(method);
                    isHideFirst = true;
                }
                // 光标的位置
                int index = editText2.getText().toString().length();
                editText2.setSelection(index);
                break;
        }
    }

}
